<?php
/**
 * Created by PhpStorm.
 * User: Kevin
 * Date: 2018/7/17
 * Time: 10:01
 */
namespace app\home\controller;
use think\Config;
use think\Controller;
use think\Db;
use EasyWeChat\Foundation\Application;

class Common extends Controller
{
    protected $_error;
    
    public function __construct()
    {
        parent::__construct();
        require_once(dirname(__FILE__).'/../conf/errorList.php');
        $this->_error = $PUBLIC_ERROR_LIST;
        header("Content-type:application/json;charset=utf-8");
    }

    /***
     * @param $user_openid
     * 获取用户手机号码
     */
    protected function getUserId($opend_id){
        $module     = strtolower(request()->module());
        $controller = strtolower(request()->controller());
        $action     = strtolower(request()->action());
        $url        = $module."/".$controller."/".$action;
        $where['user_openid'] = $opend_id;
        $res = Db::table('up_u_user')->where($where)->find();
        if($res['user_phone']==''){
            if($url!='home/my/myphone'&&$url!='home/login/userargement'){
                $this->redirect(url('my/myphone'));
            }
        }
    }
    /**
     * 验证唯一
     * @param $uid 用户id  0代表游客
     * @param $time 时间
     * @param $value 加密值
     * @param $reqKey 加密key
     * var reqKey = MD5(appId + "XW" + appkey + "XW" + $time);
     * var Token = MD5($uid + "XW" + token + "XW" + $time);
     * @return string
     */
    public  function checkAll($uid,$time,$value,$reqKey){
        header("Access-Control-Allow-Origin:*"); //允许跨域请求
        if($uid == 0){
            return true;
        }else{
            $user = Db::table('up_u_user')->where('user_id',$uid)->find();
            $data['user_last_login'] = date('Y-m-d H:i:s',time());
            Db::table('up_u_user')->where('user_id',$uid)->update($data);
            $token = $user['user_token'];
            $appId = "A6070308312682";
            $appkey = "9AF807B0-BE12-F521-6998-6D57B0CCE8BB";
            $myreqKey = md5($appId . 'XW' . $appkey . 'XW' . $time);
            $myvalue = md5($uid . 'XW' . $token . 'XW' . $time);
            if($myvalue != $value || $myreqKey != $reqKey){
                return false;
            }else{
                return true;
            }
        }
    }
    
    /**
     * 对返回信息的统一处理
     * @param $data 成功需要返回的信息
     * @param $go 是否需要继续对信息进行处理
     * @param $ext 扩展字段数组
     */
    protected function apiSuccess($data = '',$extra = '')
    {
        $info['status'] = '200';
        $info['msg']= '成功';
        if ($data || is_array($data)) {
            $info['data'] = $data;
        }
        if($extra){
            foreach ($extra as $key=>$value){
                $info[$key] = $value;
            }
        }
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
    }
    
    /***
     * @param $code
     * @param string $msg
     * 错误返回信息
     */
    protected function apiError($code, $msg = '')
    {
        if (!$msg) {
            $info['msg'] = $this->_error[$code]['msg'];
        } else {
            $info['msg'] = $msg;
        }
        $info['status'] = $code;
        $returnInfo = json_encode($info, JSON_UNESCAPED_UNICODE);
        echo $returnInfo;
        exit();
    }

    /**
     * 极光推送
     * @param $type 1:推送个人  2:推送全体
     * @param $alias 别名 user_id OR token
     * @param $message 推送消息内容
     * @param $extras 扩展字段接受数组
     * @return array
     */
    public function Jpush($type,$alias,$message,$extras)
    {
        $alias = (string)$alias;
        import('jpush.autoload', EXTEND_PATH);
        //初始化JPushClient
        $client = new \JPush\Client(config('jpush')['appKey'],config('jpush')['masterSecret']);
        //生成推送Payload构建器
        $push = $client->push();
        //推送平台 'all'  OR  ['ios','android']  OR  'ios','android'
        $push->setPlatform('all');
        //1:推送个人  2:推送全体
        if($type==1){
            $push->addAlias($alias);//按别名推送
        }else{
            $push->addAllAudience();//广播消息推送
        }
        //IOS推送
        $push->iosNotification($message, [
                'alert'=>$message,
                'badge' => '+1',
                'extras' => $extras,
                'sound'=>'default'
            ]
        );
        //Android推送
        $push->androidNotification($message, [
                'alert'=>$message,
                'extras' => $extras
            ]
        );
        return $push->send();
    }

    /**
     * uploadLocality图片上传至本地&压缩
     */
    public function uploadLocality(){
        $file = request()->file('image');
        $dir = ROOT_PATH . 'public' . DS . 'uploads/images';
        if(!file_exists($dir)){
            //检查是否有该文件夹，如果没有就创建，并给予最高权限
            mkdir($dir, 0700,true);
        }
        $url =  "http://".$_SERVER['HTTP_HOST'];
        $info = $file->validate(['size'=>2048*1024*2,'ext'=>'jpg,png,jpeg'])->move($dir);
        if($info){
            $newName = $info->getSaveName();
            //压缩图片
            image_png_size_add(ROOT_PATH . 'public' . DS . 'uploads/images/'.$newName,ROOT_PATH . 'public' . DS . 'uploads/images/'.$newName);
            echo "{$url}/uploads/images/{$newName}";
        }else{
            return json(['code'=>100,'msg'=>$file->getError()]);
        }
    }
    


    public function getOpenid()
    {
        $config = Config::get('wechat');
        $config['oauth'] = [
            'scopes' => ["snsapi_userinfo"],
            'callback' => '/home/Common/callback',//
        ];
        Config::set('wechat',$config);
        $app = new Application($config);
        $oauth = $app->oauth;
        if (empty(session('wechat_user')['avatar'])) {
            $oauth->redirect()->send();
            // 这里不一定是return，如果你的框架action不是返回内容的话你就得使用;
            // $oauth->redirect()->send();
        } else {
            $data = array();

            $data['user_openid'] = session('wechat_user')['original']['unionid'];
            $data['user_wx_image'] = session('wechat_user')['avatar'];
            $data['user_wx_nickname'] = session('wechat_user')['nickname'];
            $data['user_wx_token'] = session('wechat_user')['original']['unionid'];
            $res = Db::table('up_u_user')->where('user_openid',$data['user_openid'])->find();
            if($res){
                if($res['user_image']==''){
                    $data['user_image'] = session('wechat_user')['avatar'];
                }
                if($res['user_username']==''){
                    $data['user_username'] = session('wechat_user')['nickname'];
                }
                Db::table('up_u_user')->where('user_openid',$data['user_openid'])->update($data);
            }else{
                $data['user_image'] = session('wechat_user')['avatar'];
                $data['user_username'] = session('wechat_user')['nickname'];
                Db::table('up_u_user')->insert($data);
            }
            $ress = Db::table('up_u_user')->where('user_openid',$data['user_openid'])->find();
            session('u_openid',$ress['user_id']);
            session('openid_pay', session('wechat_user')['original']['openid']);//用户openid
            return $data['user_openid'];
        }
    }

    public function callback()
    {
        $config = Config::get('wechat');
        $app = new Application($config);
        $oauth = $app->oauth;
        $user = $oauth->user();
        session('wechat_user',$user->toArray());
        $data = array();
        $data['user_openid'] = session('wechat_user')['original']['unionid'];
        $data['user_wx_image'] = session('wechat_user')['avatar'];
        $data['user_wx_nickname'] = session('wechat_user')['nickname'];
        $data['user_wx_token'] = session('wechat_user')['original']['unionid'];
        $res = Db::table('up_u_user')->where('user_openid',$data['user_openid'])->find();
        if($res){
            if($res['user_image']==''){
                $data['user_image'] = session('wechat_user')['avatar'];
            }
            if($res['user_username']==''){
                $data['user_username'] = session('wechat_user')['nickname'];
            }
            Db::table('up_u_user')->where('user_openid',$data['user_openid'])->update($data);
        }else{
            $data['user_image'] = session('wechat_user')['avatar'];
            $data['user_username'] = session('wechat_user')['nickname'];

            Db::table('up_u_user')->insert($data);
        }
        $ress = Db::table('up_u_user')->where('user_openid',$data['user_openid'])->find();

        session('u_openid',$ress['user_id']);
        session('openid_pay', session('wechat_user')['original']['openid']);//用户openid
        header('location:'. session('target_url'));
    }
    
    /**
     * 获取时间
     * @return array
     */
    public function getDateBytimeDate($string){
        $replacement = '-';
        $replacement2 = ':';
        $a = substr_replace($string, $replacement, 4, 0);
        $b = substr_replace($a, $replacement, 7, 0);
        $c = substr_replace($b, ' ', 10, 0);
        $d = substr_replace($c, $replacement2, 13, 0);
        $e = substr_replace($d, $replacement2, 16, 0);
        return $e;
    }

}